﻿using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Core.Serializer;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Plug.MQService;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Loader;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ec.NETCoreFramework.Common.Plug.QuartzService
{
    public class MQHostedService : BackgroundService
    {
        private readonly ILogger<MQHostedService> _logger;
        private readonly AppConfig _config;
        private readonly MsgConsume _msgConsume;

        public MQHostedService(ILogger<MQHostedService> logger,
            MsgConsume msgConsume,
            AppConfig config)
        {
            _logger = logger;
            _config = config;
            _msgConsume = msgConsume;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {

            var listDll = new List<TaskInterface>();
            var path = Path.Combine(Directory.GetCurrentDirectory(), "plandll"); ;
            var files = Directory.GetFiles(path).Where(f => f.Contains("MQ")).ToArray();

            // 记录当前文件信息和对象信息
            var fileInfolist = new Dictionary<string, TaskInterface>();
            var _AssemblyLoadContext = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
            foreach (var item in files)
            {
                var index = -1;
                if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
                {
                    index = item.LastIndexOf("\\");
                }
                else
                {
                    index = item.LastIndexOf("/");
                }

                var jobConfig = _config.GetJob(item.Substring(index + 1));
                if (jobConfig == null) continue;
                using (var fs = new FileStream(item, FileMode.Open, FileAccess.Read))
                {

                    var assembly = _AssemblyLoadContext.LoadFromStream(fs);//可以直接读数据库																		  

                    var type = assembly.GetExportedTypes().Where((t) =>
                    {
                        return t.BaseType.Name == typeof(TaskInterface).Name;
                    }).FirstOrDefault();
                    foreach (var q in jobConfig.Consumes)
                    {
                        var fileInfo = new FileInfo(item);
                        string fileName = fileInfo.Name + "-" + q.UnionId;
                        TaskInterface currentJob = Activator.CreateInstance(type) as TaskInterface;

                        q.Secret = _config.ReqAppSecret.Secret;
                        q.AppId = _config.ReqAppSecret.AppId;
                        //设置队列名称
                        currentJob.SetConsumeConfig(ProtoBufSerializer.Serializeby(q));
                        //最后修改时间
                        currentJob.FileInfoLastTime = fileInfo.LastWriteTime;
                        fileInfolist.Add(fileName, currentJob);

                        _msgConsume.Consume(currentJob);

                    }
                }

            }
            await Task.CompletedTask;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                
                await Task.Delay(1000, stoppingToken);
            }
        }
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            if (_msgConsume != null)
            {
                _msgConsume.Close();
            }
            await Task.CompletedTask;
        }
       
    }
}
